from codeflow import settings
from codeflow.browser.models import get_scm_client, Changeset
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth.decorators import login_required
import pysvn

def html_diff(request):
    "Returns a HTML fragment with a diff of a file in the specified changeset"
    # FIXME: Quick & Dirty!
    scm = get_scm_client()
    path = request['path']
    cset_scm_id = request['changeset_scm_id']
    cset, created = Changeset.objects.get_or_create(scm_id=cset_scm_id)
    try:
        current_content = scm.cat(settings.CODEFLOW_SCM_REPO + path,
                                  revision=cset._get_rev(),
                                  peg_revision=cset._get_rev())
    except pysvn.ClientError:
        current_content = ""
    try:
        previous_content = scm.cat(settings.CODEFLOW_SCM_REPO + path,
                                   revision=cset._get_previous_rev(),
                                   peg_revision=cset._get_rev())
    except pysvn.ClientError:
        previous_content = ""
    import difflib
    hd = difflib.HtmlDiff(4, 80)
    context_diff = not request.has_key('complete')
    table = hd.make_table(previous_content.splitlines(),
                          current_content.splitlines(),
                          "%s (rev %s)" % (path.encode('utf8'),
                                           int(cset.scm_id) - 1),
                          "%s (rev %s)" % (path.encode('utf8'), cset.scm_id),
                          context=context_diff)

    return HttpResponse(table)

def browse_path(request, path):
    "Shows the content of some path in the SCM"
    scm = get_scm_client()
    url = settings.CODEFLOW_SCM_REPO + "/" + path
    content = None
    entries = []
    log_messages = []
    try:
        # The path is either a file...
        content = scm.cat(url)
    except:
        # ...or a directory
        entries = [{'relative_name': entry['name'][len(url):]}
                    for entry in scm.ls(url)]
    changesets = [Changeset.objects.get_or_create(scm_id=log['revision'].number)[0]
                  for log in scm.log(url, limit=20)]

    return render_to_response('codeflow/browser/browse_path.html',
                              {'path': path,
                               'content': content,
                               'entries': entries,
                               'changesets': changesets},
                              context_instance=RequestContext(request))
browse_path = login_required(browse_path)

def home(request):
    return HttpResponseRedirect("/browse/file/")
